from waveapi import events
from waveapi import robot
from waveapi import element
from waveapi import ops
from waveapi import appengine_robot_runner

import gdata.base.service
import gdata.service
import gdata.alt.appengine
try:
  from xml.etree import ElementTree 
except ImportError:
  from elementtree import ElementTree 
import atom 
import gdata.base

import urllib

def OnRobotAdded(event, wavelet):
  """Invoked when the robot has been added."""
  badge = 'http://recipe-bot.appspot.com/images/recipe-bot-badge.png'
  image = element.Image(badge)
  blip = wavelet.root_blip.reply()
  blip.append(image)
  greeting = "\nSimply ask for a recipe using the following keywords:\n\
    'recipe for [list of ingredients] ?'\n\
    Example: recipe for chicken pizza?\n\
    Don't forget to end your request with a question mark (?)"
  blip.append(greeting)

def OnBlipSubmitted(event, wavelet):
  """Invoked when a blip is sent to the wavelet.
  If it ends in a question mark, we look for the start of the request.
  Based on the words 'recipe for' ... '?' (keywords are within this string)"""
  contents = event.blip.text
  
  #Check to see if the last letter is a question mark.
  if contents.endswith('?'):
    str_match = contents.partition('recipe for ')
    if str_match[2] != '':
      blip = event.blip
      keywords = str_match[2].rstrip('?')
      
      #Pass the keywords and Blip ID to the getGoogleBase function
      getGoogleBase(keywords, blip, wavelet)

def getGoogleBase(keywords, blip, wavelet):
  """Makes a request for recipes from Google Base using keywords.
  No authentication is needed, as this is a read-only request."""
  
  status_update = '\n\nSending a request to Google Base for ' + keywords + ' recipes...'
  start = len(blip.text)
  end = start + len(status_update)
  blip.append(status_update)
  
  gb_client = gdata.base.service.GBaseService()
  gdata.alt.appengine.run_on_appengine(gb_client)
  q = gdata.base.service.BaseQuery()  
  q.feed = '/base/feeds/snippets'  
  q['start-index'] = '1'  
  q['max-results'] = '5'
  url_keywords = urllib.quote_plus(keywords)
  q.bq = '[item type:recipes][keywords:' + url_keywords + ']' 
  feed = gb_client.QuerySnippetsFeed(q.ToUri())
  
  if len(feed.entry) > 0:
    child_blip = blip.reply()
    child_blip.append('\nFound the following recipes:')
    #Loop through the feed and get the recipe info
    for entry in feed.entry:
      title = entry.title.text
      description = entry.content.text
      link = entry.link[0].href
      title_link = '<a href="' + link + '">' + title + '</a>'
      favicon = getFavicon(link)
      image = element.Image(favicon)
      recipe = ' %s\n%s' % (title_link, description)
      title_length = len(title)
        
      child_blip.append('\n\n')
      child_blip.append(image)
      child_blip.append_markup(recipe)
  else:
    blip.reply().append('\nSorry, no recipes found for ' + keywords)
    
  blip.range(start, end).delete()
  
def getFavicon(link):
  url_text = link.partition('://')
  url_text = url_text[2].partition('/')
  image_link = 'http://www.google.com/s2/favicons?domain=' + url_text[0]
  return image_link

if __name__ == '__main__':
  recipeBot = robot.Robot('Recipe Bot',
      image_url='http://recipe-bot.appspot.com/images/icon.png',
      profile_url='http://recipe-bot.appspot.com/')
  recipeBot.register_handler(events.WaveletSelfAdded, OnRobotAdded)
  recipeBot.register_handler(events.BlipSubmitted, OnBlipSubmitted)
  appengine_robot_runner.run(recipeBot) 